package cn.akwing.sms.controller;

import cn.akwing.sms.pojo.*;
import cn.akwing.sms.service.AwardsService;
import cn.akwing.sms.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/awards")
public class AwardsController {
    @Autowired
    private AwardsService awardsService;
    @Autowired
    private FileService fileService;

    @RequestMapping(value = "/upload")
    public Map<String,Object> upload(MultipartFile file, HttpSession session,
                                     String text, String text1){
        Map<String ,Object> map = new HashMap<>();
        Awards awards;
        Admin admin;
        Teacher teacher;
        Student student;
        if(!file.isEmpty() && !text.isEmpty() && !text1.isEmpty()){
            System.out.println("文件非空！");
            System.out.println("标题：" + text);
            System.out.println("描述：" + text1);
            System.out.println("上传文件名："+ file.getOriginalFilename());

            awards = new Awards();
            switch ((Integer) session.getAttribute("userType")) {
                case 1:
                    admin = (Admin) session.getAttribute("userInfo");
                    awards.setId(admin.getId());
                    awards.setName(admin.getName());
                    break;
                case 2:
                    teacher = (Teacher) session.getAttribute("userInfo");
                    awards.setId(teacher.getId());
                    awards.setName(teacher.getName());
                    break;
                default:
                    student = (Student) session.getAttribute("userInfo");
                    awards.setId(student.getId());
                    awards.setName(student.getName());
                    break;
            }
            awards.setTitle(text);
            awards.setDes(text1);
            String finalName =  fileService.upLoadFile(file,map,awards.getId());
            if("error".equals(finalName)){
                return map;
            }else {
                awards.setUrl(finalName);
                awardsService.insert(awards);
                map.put("mes","上传成功！");
            }
        }else {
            map.put("mes","一些文件为空，上传失败！");
            System.out.println("一些文件为空，无法使用！");
        }
        return map;
    }

    @RequestMapping(value = "/selectAll")
    public List<Awards> selectAll(){
        return awardsService.selectAll();
    }
}
